<template>
  <div>
    <!-- 增加部门 -->
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm" label-position="right">
      <el-form-item label="名称：" prop="deptName">
        <el-input v-model="ruleForm.deptName" />
      </el-form-item>
      <!-- <el-form-item label="医院:" prop="hospitalId">
        <el-select v-model="ruleForm.hospitalId" placeholder="请选择" @change="nameSelect">
          <el-option v-for="item in options" :key="item.id" :label="item.hospitalName" :value="item.id" />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="联系人：">
        <el-input v-model="ruleForm.contact" />
      </el-form-item>
      <el-form-item label="联系电话：">
        <el-input v-model="ruleForm.tel" />
      </el-form-item> -->
      <el-form-item label="上级部门：">
        <el-cascader ref="cascader" style="width:100%" :options="tableData" :props="propsOption" :value="ruleForm.pids" clearable class="el-select-y" @change="classificationContent" />
      </el-form-item>
      <el-form-item label="主管人员：">
        <el-select v-model="ruleForm.contact" filterable clearable placeholder="输入姓名、手机号搜索" :filter-method="personnelSearch" class="el-select-y">
          <el-option
            v-for="item in departmentUserListCopy"
            :key="item.id"
            :label="item.usrName"
            :value="item.usrName"
          >
            <span style="float: left">{{ item.usrName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="治疗科室：">
        <el-checkbox v-model="ruleForm.cureDept" />
      </el-form-item>
      <el-form-item v-if="ruleForm.cureDept" label="操作员">
        <el-select v-model="idList" filterable multiple clearable placeholder="输入姓名、手机号搜索" :filter-method="operatorSearch" class="el-select-y" @change="operatorChange">
          <el-option
            v-for="item in operatorListCopy"
            :key="item.id"
            :label="item.usrName"
            :value="item.id"
          >
            <span style="float: left">{{ item.usrName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
          </el-option>
        </el-select></el-form-item>
      <el-form-item label="状态：" prop="status">
        <el-radio v-model="ruleForm.status" label="启用" />
        <el-radio v-model="ruleForm.status" label="停用" />
      </el-form-item>
      <!-- <el-form-item>
        <el-button class="submit" :loading="loading" @click="submitForm('ruleForm')">保存</el-button>
      </el-form-item> -->
    </el-form>
  </div>
</template>
<script>
export default {
  props: {
    row: {
      type: Object,
      default: () => ({}),
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
    pids: {
      type: Array,
      default: () => ([]),
    },
    currentId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      value: '',
      options: [],
      ruleForm: {
        status: "启用",
      },
      tableData: [],
      rules: {
        deptName: [
          { required: true, message: '请输入名称', trigger: 'blur' },
        ],
      },
      loading: false,
      propsOption: {
        value: 'id',
        label: 'deptName',
        children: 'children',
        checkStrictly: true, // 选择任意一项
      },
      departmentUserList: [],
      departmentUserListCopy: [],
      operatorList: [],
      operatorListCopy: [],
      idList: [],
    };
  },
  watch: {
    isEdit: {
      handler(val) {
        if (val && this.row.id) {
          this.ruleForm = this.row;
          let isTrue = false;
          if (this.ruleForm.cureDept === "true") isTrue = true;
          this.$set(this.ruleForm, 'cureDept', isTrue);
          if (this.ruleForm.operatingPersonnelId) {
            this.idList = this.ruleForm.operatingPersonnelId.split(",");
          }
        }
      },
      immediate: true, // 立即触发
    },
    pids: {
      handler(val) {
        this.$nextTick(function() {
          this.$set(this.ruleForm, 'pids', val);
          this.$set(this.ruleForm, 'pid', val[val.length - 1] ? val[val.length - 1] : 0);
        });
      },
      immediate: true, // 立即触发
    },
  },
  mounted() {
    this.getAllHospital();
    this.getList();
    this.findAllByDeptId();
    this.fetchAllUsr();
  },
  methods: {
    // 获取全部医院人员
    async fetchAllUsr() {
      const res = await this.$api['doctor/consulting/getAllUsr']();
      if (res.code !== 200) return this.$message.error('查询操作人员失败！');
      this.operatorList = res.data;
      this.operatorListCopy = JSON.parse(JSON.stringify(this.operatorList));
    },
    async findAllByDeptId() {
      const res = await this.$api['data/dept/findAllByDeptId']({ deptId: this.row && this.isEdit ? this.row.id : "" });
      if (res.code !== 200) return;
      this.departmentUserList = res.data;
      this.departmentUserListCopy = JSON.parse(JSON.stringify(this.departmentUserList));
      this.operatorCopy = JSON.parse(JSON.stringify(this.departmentUserList));
    },
    async getAllHospital() {
      const res = await this.$api['data/dept/getAllHospital']();
      if (res.code !== 200) return;
      this.options = res.data;
    },
    getList() {
      this.loading = true;
      this.$api['data/dept/deptTreeList']({
        page: 1,
        pageSize: 999999,
      }).then(res => {
        if (res.code !== 200) return;
        if (this.currentId) {
          this.tableData = this.tableDataListHandle(res.data.result);
        } else {
          this.tableData = res.data.result;
        }
      }).finally(() => (this.loading = false));
    },
    tableDataListHandle(list) {
      list.forEach((item, index) => {
        if (item.id === this.currentId) {
          item.disabled = true;
        }
        if (item.children && item.children.length > 0) {
          item.children = this.tableDataListHandle(item.children);
        }
      });
      return list;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) return;
        this.loading = true;
        if (!this.ruleForm.cureDept) this.ruleForm.cureDept = false;
        if (!this.isEdit) {
          this.$api['data/dept/hisdept']({
            ...this.ruleForm,
            // dataLevel: this.row.dataLevel ? (this.row.dataLevel + 1) : 0,
            pid: this.ruleForm.pid ? this.ruleForm.pid : 0,
            // hospitalId: this.row.hosId,
          }).then(res => {
            if (res.code !== 200) return;
            this.$emit('success');
            this.msgSuccess('增加部门成功');
          }).finally(() => (this.loading = false));
        } else {
          this.$api['data/dept/update']({
            ...this.ruleForm,
            // hospitalId: this.row.hosId,
          }).then(res => {
            if (res.code !== 200) return;
            this.$emit('success');
            this.$emit('update:isEdit', false);
            this.msgSuccess('修改部门成功');
          });
        }
      });
    },
    nameSelect(id) {
      this.options.forEach(item => {
        if (item.id === id) {
          this.ruleForm.hospitalName = item.hospitalName;
        }
      });
    },
    classificationContent(val) {
      if (val && val.length > 0) {
        const selectObject = this.$refs['cascader'].getCheckedNodes();
        this.ruleForm.pid = val[val.length - 1];
        this.ruleForm.pname = selectObject[0].label;
      } else {
        this.ruleForm.pid = undefined;
        this.ruleForm.pname = undefined;
      }
    },
    personnelSearch(val) {
      this.departmentUserListCopy = this.listHandle(val, this.departmentUserList);
    },
    operatorSearch(val) {
      this.operatorListCopy = this.listHandle(val, this.operatorList);
    },
    listHandle(val, originalList) {
      let list = [];
      if (val) {
        originalList.forEach(item => {
          if (item.usrName.indexOf(val) > -1 || item.phone.indexOf(val) > -1) list.push(item);
        });
      } else {
        list = JSON.parse(JSON.stringify(originalList));
      }
      return list;
    },
    operatorChange(idList) {
      if (idList.length === 0) {
        this.ruleForm.operatingPersonnelId = undefined;
        this.ruleForm.operatingPersonnelName = undefined;
        return;
      }
      const ids = [];
      const name = [];
      idList.forEach(id => {
        this.operatorList.forEach(item => {
          if (item.id === id) {
            ids.push(item.id);
            name.push(item.usrName);
          }
        });
      });
      this.ruleForm.operatingPersonnelId = ids.join(",");
      this.ruleForm.operatingPersonnelName = name.join(",");
    },
  },
};
</script>
<style lang="scss" scoped>
.el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
  margin-bottom: 18px;
}
</style>
